package com.tianquan.client.handler;

import com.tianquan.client.registry.ClientInstanceManager;
import com.tianquan.common.instance.ServiceInstance;
import com.tianquan.common.message.ServiceUpdateMessage;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;
import java.util.Set;

/**
 * @Author: tianquan
 * @date: 2024-11-04  10:26
 * @Description: 服务变更处理器
 */
@Slf4j
public class ServiceUpdateMessageHandler extends SimpleChannelInboundHandler<ServiceUpdateMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, ServiceUpdateMessage serviceUpdateMessage) throws Exception {
        if (serviceUpdateMessage.isSuccess()) {
            log.info("time：{},{}", serviceUpdateMessage.getLocalDateTime(), serviceUpdateMessage.getReason());
            log.info("------------------服务变更 重新同步数据----------------");
            Map<String, Set<ServiceInstance>> instances = serviceUpdateMessage.getInstances();
            log.info("需要同步的服务列表：{}", instances);
            ClientInstanceManager.clear();
            log.info("clear后的：{}", ClientInstanceManager.getInstances());
            // 更新本地服务实例列表
            instances.forEach((serviceName, serviceInstances) -> {
                for (ServiceInstance serviceInstance : serviceInstances) {
                    ClientInstanceManager.registerInstance(serviceName, serviceInstance);
                }
            });
            log.info("更新完后本地服务实例列表{}", ClientInstanceManager.getInstances());
        }
    }
}
